import axios from "axios";
import { AxiosRequestConfig, AxiosResponse } from "axios";
import { showFailToast, showLoadingToast, closeToast } from 'vant';
import { useUserStore } from "../stores/useUserStore";

let baseURL = import.meta.env.VITE_API_HOST;
axios.defaults.baseURL = baseURL; //process.env.ApiHost;
axios.defaults.timeout = import.meta.env.VITE_API_TIMEOUT;

axios.interceptors.request.use((cfg) => {
  let userUseStore = useUserStore();
  cfg.baseURL = baseURL;
  closeToast();
  showLoadingToast({
    message: '加载中...',
    forbidClick: true,
  });
  let token: string = userUseStore.token;//.getToken();
  if (token) {
    cfg.headers.authorization = "Bearer " + token;
  }
  if (cfg.method == "get") {
    cfg.data = {};
  }
  //cfg.headers = { "Content-Type": "application/json;chartset=utf-8;", ...cfg.headers } //cfg.headers["Content-Type"] = "application/json;chartset=utf-8;"
  //cfg.headers.setContentType("application/json");
  return cfg;
}, err => {

  console.log(err);
});
/* 响应拦截器 */
axios.interceptors.response.use((response: AxiosResponse) => {

  closeToast()
  const { code, msg, data } = response.data;
  // 根据自定义错误码判断请求是否成功
  if (code === 200) {
    // 将组件用的数据返回
    return Promise.resolve(data);
  } else {
    // 处理业务错误。
    //Message.error(message)
    console.log("showFailToast", msg);

    showFailToast(msg);//
    return Promise.reject(msg)
  }
}, (error) => {
  // 处理 HTTP 网络错误
  let message = ''
  // HTTP 状态码
  const status = error.response?.status
  switch (status) {
    case 401:
      message = 'token 失效，请重新登录'
      // 这里可以触发退出的 action
      var url = "/#/login?retUrl=" + window.location.pathname
      window.location.href = (url);
      break;
    case 403:
      message = '拒绝访问'
      break;
    case 404:
      message = '请求地址错误'
      break;
    case 500:
      message = '服务器故障'
      break;
    default:
      message = '网络连接故障'
  }

  showFailToast(message);
  return Promise.reject(error)
})


/* 导出封装的请求方法 */
export const http = {
  get<T = any>(url: string, params?: {} | object | null): Promise<T> {
    console.log(params);
    return axios.get(url, { params })
  },

  post<T = any>(url: string, data?: object, config?: AxiosRequestConfig): Promise<T> {
    return axios.post(url, data, config)
  },

  put<T = any>(url: string, data?: object, config?: AxiosRequestConfig): Promise<T> {
    return axios.put(url, data, config)
  },

  delete<T = any>(url: string, config?: AxiosRequestConfig): Promise<T> {
    return axios.delete(url, config)
  }
}